package q1_50.q1_10;

import java.util.HashSet;
import java.util.Set;

public class Solution3 {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0) return 0;
        int maxlen = 0;
        for (int i = 0; i < s.length(); i++) {
            for (int j = i; j < s.length(); j++) {
                String sub = s.substring(i, j + 1);
                HashSet<Character> hashMap = new HashSet<>();
                boolean flag = true;
                int length = sub.length();
                for (int k = 0; k < length; k++) {
                    if (!hashMap.add(sub.charAt(k))) {
                        flag = false;
                        break;
                    }
                }
                if (flag && length > maxlen) {
                    maxlen = length;
                }
            }
        }
        return maxlen;
    }

    /*滑动窗口模板
    //外层循环扩展右边界，内层循环扩展左边界
    for (int l = 0, r = 0 ; r < n ; r++) {
            //当前考虑的元素
            while (l <= r && check()) {//区间[left,right]不符合题意
                //扩展左边界
            }
            //区间[left,right]符合题意，统计相关信息
        }*/
    public int lengthOfLongestSubstring2(String s) {
        // 哈希集合，记录每个字符是否出现过
        Set<Character> hashSet = new HashSet<>();
        int n = s.length();
        // 右指针，初始值为 -1，相当于我们在字符串的左边界的左侧，还没有开始移动
        int left = 0, ans = 0;
        for (int right = 0; right < n; right++) {
            while (!hashSet.add(s.charAt(right))) {
                hashSet.remove(s.charAt(left));
                left++;
            }
            hashSet.add(s.charAt(right));
            // 第 left 到 right 个字符是一个极长的无重复字符子串
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }

    public int lengthOfLongestSubstring3(String s) {
        int left = 0, length = 0, max = 0;
        char[] charArray = s.toCharArray();
        for (int right = 0; right < s.length(); right++) {
            for (int k = left; k < right; k++) {
                if (charArray[k] == charArray[right]) {
                    left = k + 1;
                    length = right - left;
                    break;
                }
            }
            length++;
            if (max < length) max = length;
        }
        return max;
    }

    public static void main(String[] args) {
        Solution3 solution3 = new Solution3();
        System.out.println(solution3.lengthOfLongestSubstring("abcabcbb"));
    }
}
